<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref } from 'vue';
import { type DataTableRowKey, NDataTable } from 'naive-ui';
import { InventoryGoods } from '@/service/api/inventory';
import SearchFilter from './modules/search-filter.vue';
import GoodsZhToolbar from './modules/toolbar.vue';
import { createColumns, loadColumnWidths, resetColumnWidths } from './modules/table-columns';

// 响应式数据
const loading = ref(false);
const selectedRowKeys = ref<DataTableRowKey[]>([]);
const dataSource = ref<any[]>([]);
const totalCount = ref(0);
const columnWidths = ref<Record<string, number>>({});
const toolbarRef = ref();
const dataTableRef = ref();

// 搜索参数 - 商品套餐特定参数
const params = reactive({
  stockId: '',
  stockName: '',
  goodsName: '',
  packModel: '',
  position: '',
  searchText: '',
  brand: '',
  goodsClass: '',
  noReserveDesc: '全部',
  productNumber: '',
  goodCreatedAt: '',
  order: '-createdAt',
  pageNum: 1,
  pageSize: 20,
  modlePrice: false,
  packingUnitPrice: false,
  isStop: false,
  goodType: 'zhGoods' as const // 固定为商品套餐类型
});

// 计算表格列配置
const tableColumns = computed(() => {
  return createColumns(columnWidths.value, params.pageNum, params.pageSize, () => {
    // 删除成功回调
    params.pageNum = 1;
    fetchGoodsZhList();
  });
});

// 计算分页配置 - 避免内联对象创建导致的响应式问题
const paginationConfig = computed(() => {
  return {
    page: params.pageNum,
    pageSize: params.pageSize,
    itemCount: totalCount.value,
    showSizePicker: true,
    pageSizes: [20, 40, 60, 80, 100],
    showQuickJumper: true,
    onUpdatePage: handlePaginationChange,
    onUpdatePageSize: handlePageSizeChange
  };
});

// 表格行属性
const rowProps = (_record: any) => {
  return {
    class: 'cursor-pointer hover:bg-gray-50'
  };
};

// 事件处理方法
const handleAdd = () => {
  // 使用全局H5Router打开商品套餐添加页面
  window.$h5Router?.openGoodZhAdd({
    onSuccess: () => {
      // 添加成功后刷新列表
      params.pageNum = 1;
      fetchGoodsZhList();
    },
    onError: () => {
      window.$message?.error('商品套餐添加页面加载失败');
    }
  });
};

const handleBatchSuccess = () => {
  selectedRowKeys.value = [];
  params.pageNum = 1;
  fetchGoodsZhList();
};

const handleResetColumnWidths = () => {
  // 重置列宽并触发表格重新渲染
  const newColumnWidths = resetColumnWidths();
  columnWidths.value = { ...newColumnWidths };
};

const handleFiltersUpdate = (newFilters: any) => {
  Object.assign(params, newFilters);
};

const handleSearch = () => {
  params.pageNum = 1;
  fetchGoodsZhList();
};

const handleReset = () => {
  // 先重置所有参数到初始状态
  Object.assign(params, {
    stockId: '',
    stockName: '',
    goodsName: '',
    packModel: '',
    position: '',
    searchText: '',
    brand: '',
    goodsClass: '',
    noReserveDesc: '全部',
    productNumber: '',
    goodCreatedAt: '',
    order: '-createdAt',
    pageNum: 1,
    pageSize: 20,
    modlePrice: false,
    packingUnitPrice: false,
    isStop: false,
    goodType: 'zhGoods' as const
  });
  // 然后刷新数据
  fetchGoodsZhList();
};

const handleTableSort = (sorter: any) => {
  // 处理排序变化
  if (sorter && sorter.columnKey) {
    const order = sorter.order === 'descend' ? '-' : '';
    params.order = order + sorter.columnKey;
    params.pageNum = 1;
    fetchGoodsZhList();
  }
};

// 处理分页变化
const handlePaginationChange = (page: number) => {
  params.pageNum = page;
  fetchGoodsZhList();
};

// 处理页面大小变化
const handlePageSizeChange = (size: number) => {
  params.pageNum = 1;
  params.pageSize = size;
  fetchGoodsZhList();
};

// 设置表格列宽监听器
const setupColumnWidthObserver = () => {
  if (!dataTableRef.value) return;

  // 使用ResizeObserver监听表格头部的尺寸变化
  const observer = new ResizeObserver(() => {
    const tableElement = dataTableRef.value?.$el?.querySelector('table');
    if (!tableElement) return;

    const headers = tableElement.querySelectorAll('thead th');
    let hasChanges = false;

    headers.forEach((header: Element, index: number) => {
      const currentWidth = (header as HTMLElement).offsetWidth;

      // 获取列配置中的key
      const column = tableColumns.value[index];
      if (column && 'key' in column && column.key && column.key !== 'selection') {
        const colKey = column.key as string;

        if (columnWidths.value[colKey] !== currentWidth && currentWidth > 0) {
          columnWidths.value[colKey] = currentWidth;
          hasChanges = true;
        }
      }
    });

    if (hasChanges) {
      localStorage.setItem('goodZhList_columnWidths', JSON.stringify(columnWidths.value));
    }
  });

  // 监听表格元素
  const tableElement = dataTableRef.value?.$el?.querySelector('table');
  if (tableElement) {
    observer.observe(tableElement);
  }

  return observer;
};

// 获取商品套餐列表数据
const fetchGoodsZhList = async () => {
  loading.value = true;

  // 调用库存助手API，遵循项目规范，不使用try-catch包装
  const response = await InventoryGoods.getGoodsZhList(params);

  if (response && !response.error) {
    // 处理成功响应
    let goodsData = [];
    let totalCountValue = 0;

    // 根据实际响应结构，商品数据和总数在不同位置
    if (Array.isArray(response.data)) {
      // response.data 直接是商品数组
      goodsData = response.data;
      // maxCount 在嵌套的 response.response.data 中
      totalCountValue = (response as any).response?.data?.maxCount || 0;
    } else if (response.data && typeof response.data === 'object') {
      // response.data 是对象的情况
      goodsData = response.data.data || [];
      totalCountValue = response.data.maxCount || 0;
    }

    // 类型安全检查
    const safeTotalCount = typeof totalCountValue === 'number' && totalCountValue >= 0 ? totalCountValue : 0;
    const safeGoodsData = Array.isArray(goodsData) ? goodsData : [];

    // 处理商品套餐数据格式
    const goodsList = safeGoodsData.map((item: any) => {
      return {
        ...item,
        // 价格格式化 - 套餐价格显示
        costPriceShow: item.costPriceShow || `￥${Number(item.costPrice || 0).toFixed(2)}`,
        scalePriceShow: item.scalePriceShow || `￥${Number(item.scalePrice || 0).toFixed(2)}`,
        retailPriceShow: item.retailPriceShow || `￥${Number(item.retailPrice || 0).toFixed(2)}`,
        // 标签数据
        tags: item.tags || []
      };
    });

    // 优化数据更新流程 - 确保响应式同步更新
    totalCount.value = safeTotalCount;

    await nextTick(() => {
      dataSource.value = goodsList;
    });
  } else {
    // API调用失败或无数据时的处理
    totalCount.value = 0;
    await nextTick(() => {
      dataSource.value = [];
    });
  }

  loading.value = false;
};

// 生命周期
onMounted(() => {
  // 加载保存的列宽设置
  columnWidths.value = loadColumnWidths();
  fetchGoodsZhList().then(() => {
    // 数据加载完成后设置列宽监听器
    nextTick(() => {
      if (dataTableRef.value) {
        setTimeout(() => {
          setupColumnWidthObserver();
        }, 100); // 确保表格完全渲染
      }
    });
  });
});
</script>

<template>
  <div class="h-screen flex flex-col bg-gray-100 p-4 text-13px">
    <!-- 工具栏 -->
    <div class="mb-4 flex items-center justify-between border border-gray-200 rounded-6px bg-white p-3 shadow-sm">
      <GoodsZhToolbar
        ref="toolbarRef"
        :selected-keys="selectedRowKeys"
        @add="handleAdd"
        @batch-success="handleBatchSuccess"
        @reset-column-widths="handleResetColumnWidths"
      />

      <SearchFilter
        v-model:filters="params"
        @search="handleSearch"
        @reset="handleReset"
        @update:filters="handleFiltersUpdate"
      />
    </div>

    <!-- 表格容器 -->
    <div class="flex-1 border border-gray-200 rounded-4px bg-white" style="overflow: auto;">
      <NDataTable
        ref="dataTableRef"
        v-model:checked-row-keys="selectedRowKeys"
        :row-key="record => record.objectId"
        :columns="tableColumns"
        :data="dataSource"
        :loading="loading"
        :pagination="paginationConfig"
        :remote="true"
        height="calc(100vh - 310px)"
        :scroll-x="1850"
        :row-props="rowProps"
        class="enterprise-table"
        empty-text="暂无商品套餐数据"
        resizable
        size="small"
        @update:sorter="handleTableSort"
      ></NDataTable>
    </div>
  </div>
</template>

<style scoped>
/* 企业级表格样式 */
:deep(.n-data-table .n-data-table-table) {
  font-size: 13px;
}

/* 表格横向滚动核心样式 */
:deep(.n-data-table .n-data-table-table-content) {
  min-width: 1850px;
}

/* 分页样式 */
:deep(.n-data-table .n-data-table__pagination) {
  padding-right: 10px;
  padding-bottom: 10px;
}
</style>